// src/store/modules/user.js

import api from '@/api' // 这里假设你有一个 api/user.js 导出了登录、获取用户信息等方法
import { getToken, setToken, removeToken } from '@/utils/auth' // localStorage 封装
import router from '@/router'

const state = {
  token: getToken(),
  name: '',
  avatar: '',
}

const mutations = {
  SET_TOKEN(state, token) {
    state.token = token
  },
  SET_NAME(state, name) {
    state.name = name
  },
  SET_AVATAR(state, avatar) {
    state.avatar = avatar
  },
}

const actions = {
  // 用户登录
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      api
        .login({ username: username.trim(), password: password })
        .then(response => {
          const { token } = response.data
          commit('SET_TOKEN', token)
          setToken(token)
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 获取用户信息
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      api
        .getUserInfo(state.token)
        .then(response => {
          const { name, avatar } = response.data
          commit('SET_NAME', name)
          commit('SET_AVATAR', avatar)
          resolve(response.data)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 退出登录
  logout({ commit, dispatch }) {
    return new Promise((resolve, reject) => {
      api
        .logout()
        .then(() => {
          commit('SET_TOKEN', '')
          commit('SET_NAME', '')
          commit('SET_AVATAR', '')
          removeToken()
          // 重置路由表，回到登录页
          dispatch('tagsView/delAllViews', null, { root: true }) // 如果你用了 tagsView
          router.push({ name: 'Login' })
          resolve()
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // 移除 Token (被动，如 401 过期)
  resetToken({ commit }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      removeToken()
      resolve()
    })
  },
}

const getters = {
  token: state => state.token,
  name: state => state.name,
  avatar: state => state.avatar,
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters,
}
